package com.usian.mongodbtest;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.usian.mongodbtest.pojo.Teacher;
import org.bson.BSONObject;
import org.bson.Document;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@SpringBootTest
@RunWith(SpringRunner.class)
public class MongoDBTestDemo {


    @Test
            public void mongoDB_Java(){
        //    1.打开连接
        MongoClient mongoClient=new MongoClient("127.0.0.1",27017);
//    2.找到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("firstTest");
//    3.找到集合
        MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("teacher");
//    执行命令 db.集合.find
        FindIterable<Document> findIterable = mongoCollection.find();
        for (Document document : findIterable) {
            System.out.println(document.get("title"));
        }
        mongoClient.close();

    }
    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void save(){
        Teacher teacher = new Teacher();
        teacher.set_id(2);
        teacher.setName("张三2");
        teacher.setAge(13);
        teacher.setCreateTime(new Date());
        mongoTemplate.save(teacher);
    }

    @Test
    public void findAll(){
        List<Teacher> list = mongoTemplate.findAll(Teacher.class);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        for (Teacher teacher:list){
            System.out.println(teacher.getName()+":"+simpleDateFormat.format(teacher.getCreateTime()));
        }
    }

    @Test
    public void findOne(){
        Teacher teacher =  mongoTemplate.findById(2,Teacher.class);
        System.out.println(teacher.getName());
    }

    @Test
    public void find(){
        Query query = new Query();
        query.limit(1);
        query.skip(1);

        Criteria criteria = Criteria.where("title").is("张三").and("age").gte(18);
        query.addCriteria(criteria);
        List<Teacher> list =  mongoTemplate.find(query,Teacher.class);
        for (Teacher teacher:list){
            System.out.println(teacher.getName());
        }
        // db.user.count();
        Long total =  mongoTemplate.count(new Query(),Teacher.class);
        System.out.println(total);
    }


}
